//
//  ChangePhoneNumViewCtrler.m
//  MIDI
//
//  Created by 千行时线 on 15/9/15.
//  Copyright (c) 2015年 QXSX. All rights reserved.
//

#import "ChangePhoneNumViewCtrler.h"
#import "AppConfig.h"
#import "CustomTextField.h"
#import "APIAdress.h"
#import "CommFunc.h"
#import "MBProgressHUD+YC.h"
#import "QXNetWorkTool.h"
#import "UserDataSingleton.h"
#import "VerificationModel.h"
#import "MBProgressHUD.h"

@interface ChangePhoneNumViewCtrler ()<QXNetWorkToolDelegate, MBProgressHUDDelegate>
{
    NSInteger timeCounter;
    NSTimer *timer;
}

@property (strong, nonatomic) IBOutlet CustomTextField  *phoneText;
@property (strong, nonatomic) IBOutlet CustomTextField  *verificationCodeText;
@property (weak, nonatomic) IBOutlet UIButton *sendVerficationCode;
@property (strong, nonatomic) VerificationModel *code;

@end

@implementation ChangePhoneNumViewCtrler

- (void)viewDidLoad
{
    [super viewDidLoad];

    //叉号，一次性删除输入框中的内容
    [self.phoneText setClearButtonMode:UITextFieldViewModeWhileEditing];
    [self.verificationCodeText setClearButtonMode:UITextFieldViewModeWhileEditing];
    
    //数字键盘
    self.phoneText.keyboardType = UIKeyboardTypeNumberPad;
    self.verificationCodeText.keyboardType = UIKeyboardTypeNumberPad;
    
    //编辑时清空
    self.phoneText.clearsOnBeginEditing = YES;
    self.verificationCodeText.clearsOnBeginEditing = YES;
    
    //placeholder字体、颜色
    [self.phoneText setFont:[UIFont fontWithName:@"Hiragino Sans GB" size:15]
                      Color:UIColorRGBA(174, 174, 174, 1)];
    
    [self.verificationCodeText setFont:[UIFont fontWithName:@"Hiragino Sans GB" size:15] Color:UIColorRGBA(174, 174, 174, 1)];
    
    self.sendVerficationCode.layer.cornerRadius = 5;
    self.sendVerficationCode.layer.masksToBounds = YES;
    [self.sendVerficationCode.layer setBorderWidth:1.0]; //边框宽度
    [self.sendVerficationCode.layer setBorderColor:UIColorRGBA(255, 255, 255, 1).CGColor];//边框颜色
    
    [self.sendVerficationCode addTarget:self action:@selector(verficationCodeSender:) forControlEvents:UIControlEventTouchUpInside];

    //手势
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap)];
    
    [self.view addGestureRecognizer:tapGestureRecognizer];
}

-(void)tap
{
    [self.phoneText resignFirstResponder];
    [self.verificationCodeText resignFirstResponder];
}

- (BOOL)isCorrectPhone
{
    if ([self.phoneText.text isEqualToString:@""])
    {
        [MBProgressHUD showError:@"请输入手机号码" toView:self.view];
        return NO;
    }
    
    if ([CommFunc isPureInt:self.phoneText.text])
    {
        if(![CommFunc isValidateMobile:self.phoneText.text])
        {
            [MBProgressHUD showError:@"请正确输入手机号" toView:self.view];
            
            return NO;
        }
    }
    else
    {
        [MBProgressHUD showError:@"请正确输入手机号" toView:self.view];
        
        return NO;
    }
    
    return YES;
}

-(void)timeFireMethod
{
    if (timeCounter < 0)
    {
        return;
    }
    
    timeCounter--;
    
    [self.sendVerficationCode setTitleColor:UIColorRGBA(230, 69, 68, 1) forState:UIControlStateNormal];
    
    self.sendVerficationCode.titleLabel.font =
    [UIFont fontWithName:DefaultFont size:12];
    
    [self.sendVerficationCode setTitle:[NSString stringWithFormat:@"重新发送(%ld)",(long)timeCounter] forState:UIControlStateNormal];
    
    self.sendVerficationCode.userInteractionEnabled = NO;
    
    if(timeCounter <= 0)
    {
        [timer invalidate];
        timer = nil;
        [self.sendVerficationCode setTitle:@"获取验证码" forState:UIControlStateNormal];
        self.sendVerficationCode.userInteractionEnabled = YES;
    }
}

//发送验证码
- (void)verficationCodeSender:(id)sender
{
    if ([self isCorrectPhone] == NO)
    {
        return;
    }
    
    [MBProgressHUD showMessage:@"正在加载" toView:self.view];
    
    QXNetWorkTool *QXnetWorkTool = [[QXNetWorkTool alloc]init];
    
    QXnetWorkTool.QXNetWorkDelegate = self;
    
    [QXnetWorkTool GetDataFromServerWithPostMethodandInterfaceName:VerificationCodeInterface andParameter:@[@{@"phone":self.phoneText.text}] tag:1];
}


-(void)pressRight:(UIButton *)sender
{
    if ([self isCorrectPhone] == NO)
    {
        return;
    }
    
    if ([self.verificationCodeText.text isEqualToString:@""])
    {
        [MBProgressHUD showError:@"请输入验证码" toView:self.view];
        return;
    }
    
    if (![self.verificationCodeText.text isEqualToString:self.code.validate_num])
    {
        [MBProgressHUD showError:@"验证码错误" toView:self.view];
        return;
    }
    
    [MBProgressHUD showMessage:@"正在加载" toView:self.view];
    
    QXNetWorkTool *QXnetWorkTool = [[QXNetWorkTool alloc]init];
    
    QXnetWorkTool.QXNetWorkDelegate = self;
    
    [QXnetWorkTool GetDataFromServerWithPostMethodandInterfaceName:
     ModifyPhoneNumberInterface andParameter:@[@{
            @"user_id":[UserDataSingleton shareInstance].user_id,
            @"phone":self.phoneText.text,
            @"code":self.code.validate_num}] tag:2];
}


- (void)GetFailResponse:(id)Response andTag:(int)tag
{
    [MBProgressHUD hideHUDForView:self.view];
    
    [MBProgressHUD showError:(NSString *)Response toView:self.view];
}

- (void)GetSuccessMessage:(id)message andTag:(int)tag
{
    switch (tag)
    {
        case 1:
        {
            [MBProgressHUD showSuccess:(NSString *)message toView:self.view];
            
            break;
        }
        case 2:
        {
            [MBProgressHUD showSuccessMultiText:@"修改成功，您可以使用新号码登陆" toView:self.view];
            
            break;
        }
    }
}

-(void)GetSuccessResponse:(id)Response andTag:(int)tag
{
    [MBProgressHUD hideHUDForView:self.view];
    
    switch (tag)
    {
        case 1:
        {
            for (NSDictionary *dic in Response)
            {
                self.code = [VerificationModel VerificationWithDict:dic];
                break;
            }
            
            timeCounter = 61;//60秒倒计时
            
            timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeFireMethod) userInfo:nil repeats:YES];
            
            break;
        }
    }
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self configNavigationItem];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void) configNavigationItem
{
    [self.tabBarController configNavigationBarTintColor:UIColorRGBA(0, 0, 0, 1)];
    [self.navigationController.navigationBar setBarTintColor:MIDIColorOfNavigationBar];
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    self.navigationItem.title = @"修改手机号码";
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],UITextAttributeTextColor, [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1.0],UITextAttributeTextShadowColor,[UIFont fontWithName:@"Hiragino Sans GB" size:18.0],UITextAttributeFont,nil]];
    
    UIButton *barButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 15)];
    //    [self configNavigationRightString:@"筛选" textFont:[UIFont fontWithName:@"Hiragino Sans GB" size:13] andAction:^{[self pressRight];}];
    [self configNavigationBackAction:^{
                [self.navigationController popViewControllerAnimated:YES];
            }];
    UIBarButtonItem *rightBar = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStyleBordered target:self action:@selector(pressRight:)];
    UIFont *rightFont = [UIFont fontWithName:@"Hiragino Sans GB" size:13.0];
    UIColor *rightColor = [UIColor whiteColor];
    
    NSDictionary * attributes = @{NSFontAttributeName:rightFont , NSForegroundColorAttributeName:rightColor };
    [rightBar setTitleTextAttributes:attributes forState:UIControlStateNormal];
    [self.navigationItem setRightBarButtonItem:rightBar];
    
}



@end
